<template>
  <a-spin :spinning="spinning">
    <div class="main">
      <a-card :title="formTile + '调样'">
        <template #extra>
          <a-button
            type="primary"
            @click="toAdd"
          >添加辅料</a-button>
          <a-button
            type="primary"
            style="margin-left:10px"
            @click="save"
            v-if="auth.includes('acc_r_s_apply_edit_save')"
          >保存</a-button>
          <a-button
            v-if="showSubmit && auth.includes('acc_r_s_apply_edit_submit')"
            type="primary"
            style="margin-left:10px"
            @click="toSubmit"
          >提交</a-button>
        </template>
        <a-table
          :scroll="{x: 1500}"
          :columns="columns"
          :pagination="false"
          :data-source="dataSource"
          bordered
        >
          <template
            v-for="col in list"
            :slot="col"
            slot-scope="text, record, index"
          >
            <div :key="col">
              <a-select
                placeholder="请选择货季"
                v-if="col == 'goodsSeason'"
                v-model="record.goodsSeason"
                style="width: 160px"
              >
                <a-select-option
                  v-for="item,i in seasonList"
                  :key="i"
                  :value="item.code"
                > {{item.name}} </a-select-option>
              </a-select>
              <a-select
                placeholder="请选择订单类别"
                v-if="col == 'category'"
                v-model="record.category"
                style="width: 160px"
              >
                <a-select-option :value="10"> 调样 </a-select-option>
                <a-select-option :value="20"> 扩色 </a-select-option>
              </a-select>

              <a-select
                placeholder="请选择"
                v-if="col == 'brand'"
                v-model="record.brand"
                style="width: 120px"
              >
                <a-select-option
                  v-for="item,i in brandList"
                  :key="i"
                  :value="item.code"
                > {{item.name}} </a-select-option>

              </a-select>
              <a-input
                style="width: 120px"
                placeholder="请输入"
                v-if="col == 'qty'"
                type="number"
                v-model="record.qty"
                :value="text"
              />
              <a-textarea
                style="width: 200px"
                placeholder="请输入"
                v-if="col == 'remark'"
                v-model="record.remark"
                :value="text"
              >
              </a-textarea>
              <a-date-picker
                v-if="col == 'limitDate'"
                v-model="record.limitDate"
                format="YYYY-MM-DD"
                valueFormat="YYYY-MM-DD"
              />

            </div>
          </template>
          <template
            slot="action"
            slot-scope="txt, record,i"
          >
            <a
              class="mr-10"
              @click="deleteItem(i)"
            >
              删除
            </a>

          </template>
        </a-table>
      </a-card>
    </div>
    <material
      v-if="showMaterial"
      @close="close"
    ></material>
  </a-spin>
</template>
  
  <script>
import { getDictChildList, retrievalsampleSave, retrievalsampleUpdate, retrievalsampleInfo, retrievalsampleSubmit } from '@api/material/index'
import material from './material.vue'
import { postAction } from '@/api/manage'

const columns = [
  {
    title: '单据编号',
    width: 200,
    dataIndex: 'accRetrievalSampleCode',
    fixed: 'left',
  },
  {
    title: '货季',
    width: 200,
    dataIndex: 'goodsSeasonValue',
    scopedSlots: { customRender: 'goodsSeason' }
  },
  // {
  //   title: '辅料品类',
  //   width: 180,
  //   dataIndex: 'accType',
  //   scopedSlots: { customRender: 'supplyCode' }
  // },
  {
    title: '订单类别',
    width: 200,
    dataIndex: 'category',
    scopedSlots: { customRender: 'category' }
  },
  {
    title: '物料代码',
    width: 200,
    dataIndex: 'accPriceCode',
    scopedSlots: { customRender: 'accPriceCode' }
  },
  {
    title: '物料名称',
    width: 120,
    dataIndex: 'accName'
  },
  {
    title: '品牌',
    width: 180,
    dataIndex: 'brand',
    scopedSlots: { customRender: 'brand' }
  },
  {
    title: '供应商',
    width: 100,
    dataIndex: 'supplyName'
  },
  {
    title: '供应商编号',
    width: 150,
    dataIndex: 'supplyCode'
  },
  {
    title: '规格',
    width: 100,
    dataIndex: 'materialSpecsName'
  },
  {
    title: '颜色',
    width: 100,
    dataIndex: 'materialColorName'
  },
  {
    title: '数量',
    width: 180,
    dataIndex: 'qty',
    scopedSlots: { customRender: 'qty' }
  },
  {
    title: '单位',
    width: 100,
    dataIndex: 'purchasingUnitValue'
  },
  {
    title: '要求货期',
    width: 200,
    dataIndex: 'limitDate',
    scopedSlots: { customRender: 'limitDate' }
  },
  {
    title: '价格',
    width: 100,
    dataIndex: 'price'
  },
  {
    title: '税率',
    width: 100,
    dataIndex: 'taxRate'
  },
  // {
  //   title: '金额',
  //   width: 100,
  //   dataIndex: 'totalAmount',
  //   scopedSlots: { customRender: 'totalAmount' }

  // },
  {
    title: '备注',
    width: 250,
    dataIndex: 'remark',
    scopedSlots: { customRender: 'remark' }
  },
  // {
  //   title: '返回原因',
  //   width: 200,
  //   dataIndex: 'rejectReason',
  //   scopedSlots: { customRender: 'rejectReason' }
  // },
  {
    title: '操作',
    width: 80,
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }
]
const data = []
data.push({
  key: data.length,
  name: '',
  time: '',
  workOrNo: 'No'
})
export default {
  components: {
    material
  },
  data() {
    return {
      key: 0,
      urlKey: 'basemgt-material/',
      data,
      columns,
      editingKey: '',
      spinning: false,
      seasonList: [],
      dataSource: [],
      brandList: [],
      showMaterial: false,
      showSubmit:false,
      formTile: '',
      accRetrievalSampleId: '',
      accRetrievalSampleCode: '',
      auth:[],
      content: {
        accPriceCode: '',
        brand: '',
        category: 0,
        goodsSeason: '',
        limitDate: '',
        price: 0,
        qty: 0,
        rejectReason: '',
        remark: '',
        supplyCode: '',
        taxRate: '',
        totalAmount: 0
      },
      list: ['accRetrievalSampleCode', 'goodsSeason', 'category', 'brand', 'qty', 'limitDate', 'remark']
    }
  },

  created() {
    this.loadData()
    this.getAuth()
    if (this.$route.query.accRetrievalSampleId) {
      this.$nextTick(() => {
        this.formTile = '编辑'
        this.showSubmit = true
        this.getDetail(this.$route.query.accRetrievalSampleId)
      })
    } else {
      this.formTile = '新增'
    }
  },
  mounted() {},
  computed: {
    jobNumber() {
      return this.$store.getters.userInfo.workNo || ''
    }
  },
  methods: {
    loadData() {
      this.getDictChildList('SMALL_BRAND', 'brandList')
      this.getDictChildList('GOOD_SEASON', 'seasonList')
    },
    getAuth() {
      const params = {
        pageCode: 'acc_r_s_apply_edit',
        jobNumber: this.jobNumber
      }
      postAction(`${this.urlKey}account/auth`, params).then(res => {
        if (res.code == 200) {
          this.auth = res.data
        }
      })
    },
    async getDictChildList(name, list) {
      const params = {
        name: name
      }
      try {
        const res = await getDictChildList(params)
        if (res.code == 200) {
          this[list] = res.data
        } else {
          if (res.msg) {
            this.$message.error(res.msg)
          } else {
            this.$message.error('获取数据字典失败！')
          }
        }
      } catch (error) {
        this.$message.error('获取数据字典失败！')
      }
    },
    async getDetail(id) {
      this.spinning = true
      const params = {
        accRetrievalSampleId: id
      }
      try {
        const res = await retrievalsampleInfo(params)
        if (res.code == 200) {
          this.dataSource = res.data.detail
          this.accRetrievalSampleCode = res.data.accRetrievalSampleCode
          this.accRetrievalSampleId = res.data.accRetrievalSampleId
        } else {
          this.$message.warning(res.msg)
        }
      } catch (error) {
        this.$message.warning('获取详情失败！')
      } finally {
        this.spinning = false
      }
    },
    toAdd() {
      this.showMaterial = true
    },
    close(selectedRows) {
      this.showMaterial = false
      console.log(selectedRows)
      if(selectedRows.length){
        if (!this.dataSource.length) {
        this.dataSource = selectedRows

      } else {
        this.dataSource = this.dataSource.concat(selectedRows)
        this.showSubmit = false
      }
      }
     
    },

    deleteItem(key) {
      // console.log(key)
      // if (this.dataSource.length === 1) {
      //   return
      // }
      this.dataSource.splice(key, 1)
    },
    async save() {
      // console.log(this.dataSource)
      const params = {
        detail: this.dataSource,
        jobNumber: this.jobNumber
      }
      if (this.accRetrievalSampleId) {
        params.accRetrievalSampleCode = this.accRetrievalSampleCode
        params.accRetrievalSampleId = this.accRetrievalSampleId
      }
      try {
        const res = this.accRetrievalSampleId ? await retrievalsampleUpdate(params) : await retrievalsampleSave(params)
        if (res.code == 200) {
          this.$message.success('保存成功！')
          if(!this.accRetrievalSampleId){
            this.accRetrievalSampleId = res.data.accRetrievalSampleId
            this.getDetail(this.accRetrievalSampleId)
          }else{
            this.getDetail(this.accRetrievalSampleId)
          }
          this.showSubmit = true
        } else {
          if (res.msg) {
            let that = this
            that.$confirm({
              title: res.msg,
              cancelText: '取消',
              onOk: res => {
                console.log(res)
                return new Promise((resolve, reject) => {
                  reject().catch(err => {
                    resolve()
                    console.log(err)
                  })
                }).catch(() => console.log('Oops errors!'))
              },
              onCancel() {}
            })
          } 
        }
      } catch (error) {
        this.$message.error('保存失败！')
      }
    },
    async toSubmit() {
      const params = {
        accRetrievalSampleId: this.accRetrievalSampleId,
        jobNumber: this.jobNumber
      }

      try {
        const res = await retrievalsampleSubmit(params)
        if (res.code == 200) {
          this.$message.success('提交成功！')
        } else {
          if (res.msg) {
            let that = this
            that.$confirm({
              title: res.msg,
              cancelText: '取消',
              onOk: res => {
                console.log(res)
                return new Promise((resolve, reject) => {
                  reject().catch(err => {
                    resolve()
                    console.log(err)
                  })
                }).catch(() => console.log('Oops errors!'))
              },
              onCancel() {}
            })
          } 
        }
      } catch (error) {
        this.$message.error('提交失败！')
      }
    },
    reset() {
      this.$emit('close')
    }
  }
}
</script>
  <style scoped>
.info-action {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: center;
  justify-content: flex-end;
}
.ml-20 {
  margin-left: 20px;
}
</style>